# -*- coding:utf-8 -*-

import logging
from logging.handlers import RotatingFileHandler
import os
from pathlib import Path

from StressAna.Lib.Model import Globalvariables


class Log(object):
    '''
    封装后的logging
    '''

    def __init__(self):
        self.logger_main = self.init_logger("main")
        self.logger_web = self.init_logger("web")
        self.logger_client = self.init_logger("client")

    def init_logger(self, log_name):
        '''
        初始化日志输出对象
        '''
        logger = logging.getLogger(log_name)
        logger.setLevel(level=logging.INFO)
        # 定义一个RotatingFileHandler，最多备份10个日志文件，每个日志文件最大1K
        log_file_path = Path(Globalvariables.get_main_root_path()).joinpath('Syslog', f"log_{log_name}.txt")
        if not Path(log_file_path).parent.exists():
            os.makedirs(Path(log_file_path).parent)
        rHandler = RotatingFileHandler(log_file_path, maxBytes=1024 * 1024, backupCount=10)
        rHandler.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s - %(lineno)d - %(message)s')
        rHandler.setFormatter(formatter)
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        console.setFormatter(formatter)
        logger.addHandler(rHandler)
        logger.addHandler(console)
        return logger

    def get_logger(self, log_name):
        if log_name == "main":
            return self.logger_main
        elif log_name == "web":
            return self.logger_web
        elif log_name == "client":
            return self.logger_client
        else:
            return self.logger_main
